import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  ScrollView,
  Image,
  TextInput,
  TouchableOpacity,
  Platform,
  DeviceEventEmitter,
  NativeAppEventEmitter
} from 'react-native';

import styles from './editOrderStyle';
import helper from '../util/helper';
import api from '../../services/api';
import DatePicker from 'react-native-datepicker';
import moment from 'moment';
import Toast from 'react-native-sk-toast';
import ToastTip from '../global/ToastTip';
import LoadingTip from '../global/LoadingTip';
import Touch from '../global/Touch';
import RNFetchBlob from 'rn-fetch-blob'
import DeviceStorage from '../global/DeviceStorage';

import KeyboardAwareScrollView from '../global/keyboardScrollView/KeyboardAwareScrollView';

class EditServiceSide extends Component {
    constructor(props) {
		super(props);

        let {data, source} = this.props;

        console.log("#######", data);

		this.state = {
            isLoading: true,
			isRefreshing: false,
			currentPage: 1,
            thirdPartyName: source=='edit'?(data.thirdPartyName||''):'',
            thirdPartyPerson: source=='edit'?(data.thirdPartyPerson||''):'',
            thirdPartyPhone: source=='edit'?(data.thirdPartyPhone||''):''
            // activeService:[1,0],
		};

		// this.props.navigator.setOnNavigatorEvent(this._onNavigatorEvent.bind(this));
	}

    _submitAction(){
        let {source, data,fileUri} = this.props;

        let {thirdPartyName, thirdPartyPerson, thirdPartyPhone} = this.state;
        let req_data = {
            ...data,
            status: source!='edit'?2:data.status,
            isThirdParty: 1,
            thirdPartyName:thirdPartyName||(source=='edit'?data.thirdPartyName:''),
            thirdPartyPerson: thirdPartyPerson||(source=='edit'?data.thirdPartyPerson:''),
            thirdPartyPhone: thirdPartyPhone||(source=='edit'?data.thirdPartyPhone:'')
        };

        if(!req_data.thirdPartyName){
            this.refs.toast.show('请输入服务方');
            return;
        }

        if(req_data.thirdPartyName.length>50){
            this.refs.toast.show('服务方不超过50个字符');
            return;
        }

        if(req_data.thirdPartyPerson && req_data.thirdPartyPerson.length>50){
            this.refs.toast.show('服务人员姓名不超过50个字符');
            return;
        }

        if(!req_data.thirdPartyPhone){
            this.refs.toast.show('请输入服务人员电话');
            return;
        }

        if(!/^\d{1,11}$/.test(req_data.thirdPartyPhone)){
            this.refs.toast.show('请输入正确的服务人员电话');
            return;
        }

        if(source != 'edit'){
            this.props.navigator.push({
                title: "确认提交订单",
    			screen: 'housekeeperapp.orderconfirm',
                backButtonTitle:'',
    			passProps: {
    				order_detail:req_data,
                    order_phone: this.props.userPhone,
                    fileUri:fileUri,
                    isPay:this.props.isPay,
                    serviceFee:this.props.serviceFee,
    			},
                navigatorStyle:{
                    tabBarHidden: true,
                    navBarTextColor: 'white',
                	navBarButtonColor: 'white',
                	navBarBackgroundColor: '#EA5404',
                    statusBarColor: '#EA5404',
                    navBarTitleTextCentered: true,
                    topBarElevationShadowEnabled:false
                },
                navigatorButtons: {
                    leftButtons:[
                        {
                            id: 'back',
                            icon: require("../../../img/hk_back_icon.png")
                        }
                    ]
                }
    		});
            return;
        }

        this.setState({loadingShow:true});
        // let url = (source == 'edit'? '/order/updateorder':'/order/createorder');
        console.log("@@@@@@", req_data);
        this._readFileToBase64(req_data);
        

    }

    async _realSubmitAction(req_data){
        let res = await api.post('/order/updateorder',req_data);
        if(res.cd == 1){
            this.refs.toast.show(res.msg);
        }else{
            if(res.data){
                this.setState({loadingShow:false});

                Toast.bottom("编辑成功");
                setTimeout(()=>{
                    this.props.navigator.popToRoot();
                    let Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter;
                    Emitter.emit("order.onload");
                }, 500);
            }
        }
    }

    _readFileToBase64(info){
        let {fileUri} = this.props;
        if (fileUri) {
            let data = ''
            RNFetchBlob.fs.readStream(
                // file path
                fileUri,
                // encoding, should be one of `base64`, `utf8`, `ascii`
                'base64',
                // (optional) buffer size, default to 4096 (4095 for BASE64 encoded data)
                // when reading file in BASE64 encoding, buffer size must be multiples of 3.
                4095)
            .then((ifstream) => {
                ifstream.open()
                ifstream.onData((chunk) => {
                  // when encoding is `ascii`, chunk will be an array contains numbers
                  // otherwise it will be a string
                  data += chunk
                })
                ifstream.onError((err) => {
                  console.log('oops', err)
                })
                ifstream.onEnd(() => {  
                    console.log('test',data);
                    data = "data:image/jpeg;base64,"+data;
                    info = {...info,remarkImage:data}
                    this._realSubmitAction(info);
                })
            })
        }else{
            info = {...info,remarkImage:''};
            this._realSubmitAction(info);
        }
        
    }

    componentDidMount(){

    }

    componentWillMount(){
        // let {source} = this.props;
        // if(source == 'edit'){
        //     return;
        // }

    }

    componentWillUnmount(){
        let {source} = this.props;

    }

    render() {
        let {data, source} = this.props;
        return (
            <View style={styles.wrapper}>
                <KeyboardAwareScrollView style={styles.container} extraScrollHeight={60}>
                    <View style={styles.formContainer}>
                        <View style={styles.formItem}>
                            <Text style={styles.leftText}>服务方</Text>
                            <TextInput
                                value={this.state.thirdPartyName}
                                defaultValue={source=='edit'?data.thirdPartyName:''}
                                onChangeText={(text)=>{this.setState({thirdPartyName:text})}}
                                style={styles.itemRight}
                                clearButtonMode={'while-editing'}
                                editable = {true}
                                multiline={Platform.OS=='ios'?false:true}
                                numberOfLines={1}
                                underlineColorAndroid={'#ffffff'}
                                placeholder={'请输入服务方'}
                                placeholderTextColor={'#B5B5B5'}
                            />
                        </View>
                        <View style={styles.formItem}>
                            <Text style={styles.leftText}>服务人员姓名</Text>
                            <TextInput
                                value={this.state.thirdPartyPerson}
                                defaultValue={source=='edit'?data.thirdPartyPerson:''}
                                onChangeText={(text)=>{this.setState({thirdPartyPerson:text})}}
                                style={styles.itemRight}
                                clearButtonMode={'while-editing'}
                                editable = {true}
                                multiline={Platform.OS=='ios'?false:true}
                                numberOfLines={1}
                                underlineColorAndroid={'#ffffff'}
                                placeholder={'请输入服务人员姓名'}
                                placeholderTextColor={'#B5B5B5'}
                            />
                        </View>
                        <View style={[styles.formItem,{borderBottomWidth:0}]}>
                            <Text style={styles.leftText}>服务人员电话</Text>
                            <TextInput
                                value={this.state.thirdPartyPhone}
                                onChangeText={(text)=>{
                                    let p = text.replace(/ /g, '').substring(0,11);
                                    this.setState({thirdPartyPhone: p});
                                }}
                                style={[styles.itemRight, {}]}
                                clearButtonMode={'while-editing'}
                                maxLength={13}
                                editable = {true}
                                keyboardType={'numeric'}
                                underlineColorAndroid={'#ffffff'}
                                placeholder={'请输入服务人员电话'}
                                placeholderTextColor={'#B5B5B5'}
                            />
                        </View>

                    </View>

                </KeyboardAwareScrollView>
                <View style={styles.submitBtnContainer}>
                    <Touch onPress={this._submitAction.bind(this)} style={styles.submitBtn}>
                        <Text style={styles.submitBtnText}>确定</Text>
                    </Touch>
                </View>
                <ToastTip ref="toast" offsetY={160}/>
                <LoadingTip show={this.state.loadingShow}/>
            </View>
        );
    }
}

var connectHelper = require('../../services/connectHelper');
EditServiceSide = connectHelper(state => state)(EditServiceSide);

module.exports = EditServiceSide;
